<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Name_FormItem" prop="Name">
							<template #label>
								<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
							</template>
							<el-input v-model="searchData.Name" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="StaffNo_FormItem" prop="StaffNo">
							<template #label>
								<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
							</template>
							<el-input v-model="searchData.StaffNo" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<WtmDeptSelector v-model="searchData.GroupId" label="部门" :rules="[]" :auth="false" />
					</el-col>

					<!-- 可展开的详细搜索条件 -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="PersonId_FormItem" prop="PersonId">
								<template #label>
									<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
								</template>
								<el-select v-model="searchData.PersonId" :data="stateData.AllSysPersons" clearable>
									<el-option v-for="item in stateData.AllSysPersons" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="JobPositionId_FormItem" prop="JobPositionId">
								<template #label>
									<WtmLabelTooltip label="工作岗位" tooltip="关联的工作岗位" />
								</template>
								<el-select v-model="searchData.JobPositionId" :data="stateData.AllSysJobPositions" clearable>
									<el-option v-for="item in stateData.AllSysJobPositions" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="JobAssignmentId_FormItem" prop="JobAssignmentId">
								<template #label>
									<WtmLabelTooltip label="分岗申请单号" tooltip="关联的分岗申请单" />
								</template>
								<el-select v-model="searchData.JobAssignmentId" :data="stateData.AllSysHrJobAssignmentRequestBills" clearable>
									<el-option
										v-for="item in stateData.AllSysHrJobAssignmentRequestBills"
										:key="item.Value"
										:value="item.Value"
										:label="item.Text"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysHrJobAssignmentRequestBillEntry/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrJobAssignmentRequestBillEntry/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysHrJobAssignmentRequestBillEntry/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrJobAssignmentRequestBillEntry/SysHrJobAssignmentRequestBillEntryExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>
		<div v-else>
			<WtmButton
				icon="fa fa-users"
				type="primary"
				:button-text="`批量分配岗位${hasSelectedRows ? ` (${selectedRowsCount})` : ''}`"
				:disabled="!hasSelectedRows"
				@click="onBatchJobAssignment()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysHrJobAssignmentRequestBillEntry/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrJobAssignmentRequestBillEntry/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrJobAssignmentRequestBillEntry/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="岗位分配明细;true;HengTong.Areas.Hr.Controllers;SysHrJobAssignmentRequestBillEntry">
import { ElMessage } from 'element-plus';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed, nextTick, type ComponentInternalInstance } from 'vue';
import { SysHrJobAssignmentRequestBillEntryApi as api } from '/@/views/hr/syshrjobassignmentrequestbillentry/api';
import {
	ISysHrJobAssignmentRequestBillEntryView,
	ISysHrJobAssignmentRequestBillEntryQuery,
} from '/@/views/hr/syshrjobassignmentrequestbillentry/api/interface';
import other from '/@/utils/other';

// 懒加载子组件
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));
const BatchJobAssignmentDialog = defineAsyncComponent(() => import('/@/components/batchJobAssignmentDialog/index.vue'));

// 表头配置
const TABLE_HEADERS = [
	{ title: '分岗申请单号', key: 'JobAssignmentName', type: 'text', isCheck: true },
	{ title: '员工姓名', key: 'Name', type: 'text', isCheck: true },
	{ title: '员工工号', key: 'StaffNo', type: 'text', isCheck: true },
	{ title: '员工', key: 'PersonName', type: 'text', isCheck: true },
	{ title: '分配工作岗位', key: 'JobPositionName', type: 'text', isCheck: true },
	{ title: '所属部门', key: 'GroupName', type: 'text', isCheck: true },
	{ title: '人事组织', key: 'OrgName', type: 'text', isCheck: true },
	{ title: '备注', key: 'EntryRemark', type: 'text', isCheck: true },
] as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysHrJobAssignmentRequestBillEntryQuery;
		/** 主表ID */
		entityId?: string | null;
		/** 传递的部门ID */
		groupId?: string | null;
		/** 传递的组织ID */
		orgId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
		groupId: null,
		orgId: null,
	}
);

const stateData = reactive({
	AllSysPersons: [],
	AllSysJobPositions: [],
	AllSysGroups: [],
	AllSysOrgs: [],
	AllSysHrJobAssignmentRequestBills: [],
});

const searchData = ref<ISysHrJobAssignmentRequestBillEntryQuery>({
	PersonId: null,
	StaffNo: null,
	Name: null,
	JobPositionId: null,
	GroupId: null,
	OrgId: null,
	JobAssignmentId: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）
	data: [],
	// 表头内容（必传，注意格式）
	header: TABLE_HEADERS,
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});

// 计算属性 - 判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

// 计算属性 - 获取选中行数
const selectedRowsCount = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length;
});

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		handleError(error);
	}
};

// 对话框操作
const OnCreateClick = () => {
	const data = props.entityId ? { entityId: props.entityId, groupId: props.groupId, orgId: props.orgId } : null;
	other.openDialog(ci.proxy?.$t('message._system.common.vm.add') || '新增', CreateDialog, data, getTableData);
};

const OnEditRowClick = (row: ISysHrJobAssignmentRequestBillEntryView) => {
	// 合并行数据和关联信息，确保编辑时也能正确传递关联ID
	const data = {
		...row,
		entityId: props.entityId,
		groupId: props.groupId,
		orgId: props.orgId,
	};
	other.openDialog(ci.proxy?.$t('message._system.common.vm.edit') || '编辑', EditDialog, data, getTableData);
};

const OnDetailsRowClick = (row: ISysHrJobAssignmentRequestBillEntryView) => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.detail') || '详情', DetailsDialog, row, getTableData);
};

const OnImportClick = () => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.import') || '导入', ImportDialog, null, getTableData);
};

// 删除操作
const onDelete = async (row: ISysHrJobAssignmentRequestBillEntryView) => {
	try {
		const ids = [row.ID] as (string | number)[];
		await api().delete(ids);
		getTableData();
	} catch (error) {
		handleError(error);
	}
};

// 批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysHrJobAssignmentRequestBillEntryView) => x.ID) as (string | number)[];

	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			tableRef.value?.clearSelection();
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy?.$t('message._system.common.vm.error') || '操作失败');
		}
	} else {
		ElMessage.error(ci.proxy?.$t('message._system.common.vm.check') || '请选择要删除的数据');
	}
};

// 导出操作
const onExport = () => {
	const selected = tableRef.value?.getSelectedRows();
	if (selected && selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 批量分配岗位
const onBatchJobAssignment = () => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];

	if (selectedRows.length === 0) {
		ElMessage.warning('请先勾选需要分配岗位的员工');
		return;
	}

	// 转换选中行为用户数据格式，用于批量分配对话框
	const selectedUsers = selectedRows
		.map((row: any) => ({
			ID: row.PersonId || row.ID,
			Name: row.Name,
			StaffNo: row.StaffNo,
			Code: row.StaffNo,
			GroupName: row.GroupName,
			DeptName: row.GroupName,
		}))
		.filter((user: any) => user.ID); // 过滤掉没有ID的记录

	// 构造传递给批量分配对话框的数据
	const dialogData = {
		selectedUsers: selectedUsers, // 已选择的用户列表
		selectedUserIds: selectedUsers.map((user: any) => user.ID), // 用户ID数组
		orgId: props.orgId, // 预填充组织ID
		groupId: props.groupId, // 预填充部门ID
		entityId: props.entityId, // 当前单据ID
	};

	// 根据是否有选中人员，动态设置对话框标题
	const dialogTitle = selectedUsers.length > 0 ? `为${selectedUsers.length}名员工批量分配岗位` : '批量分配岗位';

	// 打开批量分配岗位对话框，传递上下文信息
	other.openDialog(dialogTitle, BatchJobAssignmentDialog, dialogData, () => {
		// 分配完成后刷新岗位分配明细数据
		getTableData();
	});
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	// 如果有entityId，自动设置搜索条件
	if (props.entityId) {
		searchData.value.JobAssignmentId = props.entityId;
	}

	try {
		// 加载表格数据
		await getTableData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
	}
});
</script>
